angular.module('ng-chrome-cast-channels', [])
    .service('ChromeCastSenderChannel', function () {

        var session = null;
        var my_namespace = null

        /*function sessionUpdateListener(isAlive) {
            console.log("sessionUpdateListener(isAlive): " + isAlive);

            var message = isAlive ? 'Session Updated' : 'Session Removed';
            message += ': ' + session.sessionId;

            if (!isAlive) {
                session = null;
            }
        };*/

        this.initialize = function (appId, namespace, success, status, error) {
            my_namespace = namespace

            initializeCastApi = function () {

                var sessionRequest = new chrome.cast.SessionRequest(appId);

                console.log('Session request', sessionRequest);

                var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
                    sessionListener,
                    function (r) {
                        console.log('Receiver availability:', r);
                        status(r);
                    });

                chrome.cast.initialize(apiConfig,
                    function () {
                        console.log('Init success');
                        success();
                    },
                    function (err) {
                        console.log('Init error', err);
                        error(err);
                    });

                function sessionListener(e) {

                    console.log('Existing session ID:' + e.sessionId);
                    session = e;
                    //session.addUpdateListener(sessionUpdateListener);
                    //session.addMessageListener(my_namespace, receiverMessage);
                    success();
                };

            };

            window['__onGCastApiAvailable'] = function (loaded, errorInfo) {
                if (loaded) {
                    initializeCastApi();
                } else {
                    console.log(errorInfo);
                    error(errorInfo);
                }
            };

        };

        this.startSession = function(success, error) {

            chrome.cast.requestSession(function (e) {
                session = e;
                success();

            }, function(e) {
                console.log('onError', e);
                error(e);
            });
        };

        this.isStarted = function() {

            if(session == undefined)
                return false;

            return session.status === chrome.cast.SessionStatus.CONNECTED;
        };

        this.stopSession = function(callback) {
            session.stop(callback, function(e) {
                console.log('onError', e);
            });
        }

        function onSuccess(message) {
            console.log("onSuccess: " + message);
        }

        this.sendMessage = function(message) {

            console.log('Sending (session, message):', session, message);

            session.sendMessage(my_namespace, message, onSuccess.bind(this, "Message sent: " + message), function(e) {
                console.log('onError', e);
            });
        };

        return this;
    })
    .service('ChromeCastReceiverChannel', function () {
        this.initialize = function (namespace, callback) {
            window.onload = function () {

                cast.receiver.logger.setLevelValue(0);
                window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
                console.log('Starting Receiver Manager');

                // handler for the 'ready' event
                castReceiverManager.onReady = function (event) {
                    console.log('Received Ready event: ' + JSON.stringify(event.data));
                    window.castReceiverManager.setApplicationState("Application status is ready...");
                };

                // handler for 'senderconnected' event
                castReceiverManager.onSenderConnected = function (event) {
                    console.log('Received Sender Connected event 22: ' + event.data);
                    console.log(window.castReceiverManager.getSender(event.data).userAgent);
                };

                // handler for 'senderdisconnected' event
                castReceiverManager.onSenderDisconnected = function (event) {
                    console.log('Received Sender Disconnected event: ' + event.data);
                    if (window.castReceiverManager.getSenders().length == 0) {
                        window.close();
                    }
                };

                // handler for 'systemvolumechanged' event
                castReceiverManager.onSystemVolumeChanged = function (event) {
                    console.log('Received System Volume Changed event: ' + event.data['level'] + ' ' +
                        event.data['muted']);
                };

                // create a CastMessageBus to handle messages for a custom namespace
                window.messageBus =
                    window.castReceiverManager.getCastMessageBus(
                        'urn:x-cast:com.google.cast.sample.helloworld');


                window.messageBus.onMessage = function (event) {
                    console.log('Message [' + event.senderId + ']: ' + event.data);
                    // display the message from the sender
                    callback(event.data);
                    // inform all senders on the CastMessageBus of the incoming message event
                    // sender message listener will be invoked
                    window.messageBus.send(event.senderId, event.data);
                }

                // initialize the CastReceiverManager with an application status message
                window.castReceiverManager.start({
                    statusText: "Application is starting"
                });
                console.log('Receiver Manager started');
            }
        };

        return this;

    });
